﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Threading;

namespace OCDStudio.SMSPPPServer
{
    class SocketServer
    {
        private int port;
        

        public int Port
        {
            get { return port; }
            set { port = value; }
        }
        
        private bool started = false;
        private OutlookSession session;
        private List<Thread> clients = new List<Thread>();

        public OutlookSession Session
        {
            get { return session; }
            set { session = value; }
        }
        private TcpListener listener;

        public TcpListener Listener
        {
            get { return listener; }
            set { listener = value; }
        }
        

        public SocketServer(int port)
        {
            
            this.port = port;
            this.session = new OutlookSession();
        }


        public void StartServer() {
            if (started) return;

            listener = new TcpListener(port);
            listener.Start();
            while (true)
            {
                try
                {
                    TcpClient cl = listener.AcceptTcpClient();
                    TcpClientWrapper wrapper = new TcpClientWrapper(this, cl);
                    Thread t = new Thread(new ThreadStart(wrapper.ManageTcpClient));
                    clients.Add(t);
                    t.Start();
                }
                catch (ThreadAbortException) {
                    listener.Stop();
                    
                    return;
                }
                
            }

        }

        public void StopServer() {
            foreach (Thread t in clients) {
                t.Abort();
            }
            listener.Stop();            
        }

        /*
        public void RemoveMe(Thread t) {
            clients.Remove(t);
        }*/


    }
}
